package com.hj.testdb.database;

import android.content.Context;

import com.hj.testdb.database.updatedatabase.MyDatabaseHelper;

import org.greenrobot.greendao.database.Database;

/**
 * 手动建的数据库单例
 * by cczhr
 * <p>
 * 问题参考网站：https://www.cnblogs.com/dsxniubility/p/6204169.html
 * https://juejin.im/entry/583bd4800ce463006ba5b8fe
 */
public class DBService {
    private static final DBService dbService = new DBService();//单例
    /**
     * 数据库是否加密的标识
     */
    private static final boolean ENCRYPTED = false;
    private static final String DB_NAME = "greedDaoDemo.db";

    private static final String DB_PASSWORD = "123456"; //加密数据库的密码
    private DaoSession daoSession;


    private DBService() {

    }

    public static DBService getInstance() {
        return dbService;
    }

    public void init(Context context) {
        MyDatabaseHelper helper = new MyDatabaseHelper(context, DB_NAME);
        DaoMaster daoMaster;
        if (ENCRYPTED) {

            daoMaster = new DaoMaster(helper.getEncryptedWritableDb(DB_PASSWORD));
        } else {

            daoMaster = new DaoMaster(helper.getWritableDatabase());

        }
        daoSession = daoMaster.newSession();

    }


    public DaoSession getDaoSession() {
        return daoSession;
    }

    /**
     * 原始sql查询
     *
     * @return
     */
    public Database getDatabase() {
        return daoSession.getDatabase();
    }

/*
   //原始 sql查询例子

  Cursor c= DBService.getInstance().getDatabase().rawQuery("select distinct name from user",null);
        if (c.moveToFirst()) {
            do {
                com.cczhr.newmyframe.utils.Log.e(c.getString(c.getColumnIndex("name")));
            } while (c.moveToNext());
        }
        c.close();

    //一般查询
       // List<User> list=userDao.queryBuilder().where(UserDao.Properties.Name.eq("222")).list();
       // List<User> list=userDao.getSession().queryRaw(User.class,"where name=? or created_at=?","1","222").list();

    //插入数据
        User user=new User();
        user.setName("222");
        user.setCreatedAt("56555");
        UserDao userDao=DBService.getInstance().getStudentDao();

        userDao.insert(user);
    */


     /*DBService.getInstance().getDaoSession().deleteAll(User.class);//删除整个表数据

   userDao.queryBuilder().where(UserDao.Properties.Name.eq(""))).buildDelete().executeDeleteWithoutDetachingEntities();//删除指定数据
     */

}
